<?php
	date_default_timezone_set('America/New_York');

	function setElementByID($elementID, $text)
	{
		echo "<script>";
		echo "document.getElementById('$elementID').innerHTML = '$text'";
		echo "</script>";
	}
	
		function concatElementByID($elementID, $text)
	{
		echo "<script>";
		echo "var current = document.getElementById('$elementID').innerHTML ;
				document.getElementById('$elementID').innerHTML = current + '$text'";
		echo "</script>";
	}
		
	function usernamePasswordPairExists($username, $password)
	{
		$username = sanitizeString($username);
		$password = sanitizeString($password);
		
		/* echo "<br />";
		// $data = file("users.txt");
		$fp = fopen("users.txt", "r");
		if(flock($fp, LOCK_SH)):
			while($line = fgetss($fp, 512)):
				$line = explode("#", $line);
				$userFromFile = sanitizeString($line[0]);
				$passwordFromFile = sanitizeString($line[1]);
				//var_dump($userFromFile, $passwordFromFile, $password, $username);
				//echo "<br />";
				if(strcmp($userFromFile, $username) == 0 && strcmp($passwordFromFile, $password) == 0):
					flock($fp, LOCK_UN);
					fclose($fp);
					return true;
				else:
					continue;
				endif;
			endwhile;
			flock($fp, LOCK_UN);
		endif;
		fclose($fp); */
		
		require_once("\private\mysqli_connect.php");
		$query = "select username, password from administrators";
		$result = $db->query($query);
		if(!$result):
			echo "<br/> No administrators have been added to the database. <br/>";
			return false;
		endif;
		
		
		$rows = $result->num_rows;
		$match = false;
		for($i = 0; $i < $rows; $i++):
			$row = $result->fetch_array();
			$current_admin_username = $row['username'];
			$current_admin_password = $row['password']; // SHA1
			// echo "Does username '$username' match '$current_admin_username' <br/>";
			// echo "and Does password '$password' match '$current_admin_password' <br/>";
			if(strcmp($current_admin_username, $username) == 0 && strcmp($current_admin_password, SHA1($password)) == 0):
				$match = true;
			else:
				continue;
			endif;
		endfor;
		if($match):
			echo "<br/>Successfully logged in as admin '$username'<br/>";
			return true;
		else:
			return false;
		endif;
	}
	
	function sanitizeString($text)
	{
		if(!isset($text) || empty($text)):
			return "";
		endif;
		/* Remove any whitespace and strip slashes */
		return stripslashes(preg_replace('/\s+/', '', $text));
	}
	
	function sanitizeStringKeepSpaces($text)
	{
		if(!isset($text) || empty($text)):
			return "";
		endif;
		/* Remove any whitespace and strip slashes */
		return trim(stripslashes($text));
	}
	
	function emptyUsernameOrPassword()
	{
		$elementID = "error";
		$usernameOrPasswordEmpty = "Please fill in your username and password.";
		include("admin_login_form.html");
		concatElementByID($elementID, $usernameOrPasswordEmpty);
	}
	
	function successfulLogin($username)
	{
		destroySession(); // clean up any lingering session data
		session_start();
		$_SESSION['admin_username'] = $username;
		$_SESSION['adminID'] = getAdminIDbyName($username);
		//createUserCookie($username);
		redirectAdminToAdminPage();
	}
	
	function getAdminIDbyName($adminName)
	{
		require('\private\mysqli_connect.php');
		$query = "select administrators.admin_id from administrators where username = '" . $adminName . "'";
		$result = $db->query($query);
		if($result):
			$row = $result->fetch_array();
			return $row['admin_id'];
		else:
			return "";
		endif;
	}
	
	function unsuccessfulLogin()
	{
		if(isset($_SESSION)):
			session_destroy();
		endif;		
		$elementID = "error";
		$errorMessage = "Username / password combo did not match. <br />";
		include("admin_login_form.html");		
		concatElementByID($elementID, $errorMessage);
	}
	
	function login($username, $password)
	{
		$username = sanitizeString($username);
		$password = sanitizeString($password);
		// if(strcmp($username,'') == 0 || strcmp($password,'') == 0):
		if(empty($username) || empty($password)):
			emptyUsernameOrPassword();
		else:
			if(usernamePasswordPairExists($username, $password)):
				successfulLogin($username);
			else:
				unsuccessfulLogin($username);
			endif;
		endif;
	}
	
	function createUserCookie($username)
	{
		$timeOffset = 24*60*60*20;
		if(isset($_POST['stayLoggedIn'])):
			setcookie("$username" . "['username']", "$username",time() + $timeOffset, "/");
			setcookie("$username" . "['stayLoggedIn']",1, time() + $timeOffset, "/");
			setcookie("lastRememberedLogin", $username, time() + $timeOffset, "/");
		else:
			setcookie("$username" . "['username']", "$username",time() + $timeOffset, "/");
			setcookie("$username" . "['stayLoggedIn']",0, time() + $timeOffset, "/");
			/* Someone new logged in. Make sure we forget them */
			setcookie("lastRememberedLogin", "", time() - 50000, "/");
		endif;		
	}
	
	function forgetRememberMeCookie()
	{
		setcookie("lastRememberedLogin","", time() - 50000, "/");
	}
	
	function adminIsLoggedIn()
	{
		if(!isset($_SESSION)):
			session_start();
		endif;
		// $cookieFound = false;
		// if(isset($_COOKIE['lastRememberedLogin']) && !(strcmp($_COOKIE['lastRememberedLogin'], "") == 0)):
			// $username = $_COOKIE['lastRememberedLogin'];

			// $cookieFound = true;
			
			// $_SESSION['admin_username'] = $username;
			// return true;
		// else:
			// /* No one was found to be logged in with a cookie */
		// endif;		
		if(isset($_SESSION['admin_username']) and !empty($_SESSION['admin_username'])):
			return true;
		else:
			return false;
		endif;
		
		return false;
	}
	
	function redirectAdminToAdminPage()
	{
		header("Location: /proj2/admin_page.php");
	}
	
	function destroySession()
	{

		session_destroy();
		
		echo "Killing session and cookies. <br />";
		var_dump($_SESSION);
		var_dump($_COOKIE);
		header("Location: /proj2/admin_login.php");
	}
	
	function displayJavascriptAlert($message)
	{
		echo "<script>";
		echo 'alert("' . $message . '");';
		echo "</script>";
	}
?>